import { reqGetRoutesByRoleId } from '@/api/menu'
import { asyncRoute } from '@/router/routes'
import { emitter } from '@/utils/bus.js'
import { getComponent } from '@/utils/getComponent '
// import { asyncMenu } from '@/api/menu'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const notLayoutRouterArr: any[] = []
const keepAliveRoutersArr: any[] = []
const nameMap: any = {}

//需添加类型

const formatRouter = (routes: any, routeMap: any) => {
  routes &&
    routes.forEach(
      (item: {
        meta: { defaultMenu: boolean }
        path: any
        name: string | number
        children: string | any[]
      }) => {
        if (item.meta.defaultMenu === true) {
          notLayoutRouterArr.push({
            ...item,
            path: `/${item.path}`,
          })
        } else {
          routeMap[item.name] = item
          if (item.children && item.children.length > 0) {
            formatRouter(item.children, routeMap)
          }
        }
      },
    )
}

const KeepAliveFilter = (routes: any) => {
  routes &&
    routes.forEach(
      (item: {
        children: any[]
        meta: { keepAlive: any }
        component: () => Promise<any>
        name: string
      }) => {
        // 子菜单中有 keep-alive 的，父菜单也必须 keep-alive，否则无效。这里将子菜单中有 keep-alive 的父菜单也加入。
        if (
          (item.children && item.children.some((ch) => ch.meta.keepAlive)) ||
          item.meta.keepAlive
        ) {
          item.component &&
            item.component().then((val) => {
              keepAliveRoutersArr.push(val.default.name)
              nameMap[item.name] = val.default.name
            })
        }
        if (item.children && item.children.length > 0) {
          KeepAliveFilter(item.children)
        }
      },
    )
}

export const useRouterStore = defineStore('router', () => {
  const keepAliveRouters = ref<any[]>([])
  const asyncRouterFlag = ref(0)
  const setKeepAliveRouters = (history: any) => {
    const keepArrTemp: any[] = []
    history.forEach((item: { name: string | number }) => {
      if (nameMap[item.name]) {
        keepArrTemp.push(nameMap[item.name])
      }
    })
    keepAliveRouters.value = Array.from(new Set(keepArrTemp))
  }
  emitter.on('setKeepAlive', setKeepAliveRouters)

  const asyncRouters = ref<any[]>([])
  const routeMap: any = {}
  // 从后台获取动态路由
  const SetAsyncRouter = async (roleIds: number) => {
    asyncRouterFlag.value++
    let baseRouter: any = [
      {
        path: '/layout',
        name: 'layout',
        component: 'views/layout/index.vue',
        meta: {
          title: '底层layout',
        },
        children: [],
      },
    ]
    const asyncRouterRes: any = await reqGetRoutesByRoleId(roleIds)
    const asyncRouter = asyncRouterRes.data
    // const asyncRouter = asyncRoute
    asyncRouter &&
      asyncRouter.push({
        path: 'reload',
        name: 'Reload',
        meta: {
          title: '',
          closeTab: true,
          visible: false,
        },
        component: 'views/error/reload.vue',
      })
    formatRouter(asyncRouter, routeMap)
    baseRouter[0].children = asyncRouter
    if (notLayoutRouterArr.length !== 0) {
      baseRouter.push(...notLayoutRouterArr)
    }
    baseRouter = getComponent(baseRouter)
    KeepAliveFilter(asyncRouter)
    asyncRouters.value = baseRouter
    return true
  }

  return {
    asyncRouters,
    keepAliveRouters,
    asyncRouterFlag,
    SetAsyncRouter,
    routeMap,
  }
})
